import type { LanguageElement, TextAsyncData, TextElement, TextGroup } from "@/utils/struct";
import { defineStore } from "pinia";
const electron = require("electron");
export const useTextStore = defineStore('textStore', {
    state: () => {
        return {
            nextId:14,
            nextLanguageId:2,
            nextGroupId: 1,  // 新增分组ID自增计数器
            groups: [] as TextGroup[],
            languages:[] as LanguageElement[],
            elements:[] as TextElement[]
        };
    },
    getters: {
    },
    actions:{
        newText():TextElement {
            let e = {id: this.nextId++, texts:new Array<string>(this.languages.length)}
            this.elements.push(e)
            return e
        },
        deleteText(id: number) {
            for (let i = 0; i < this.elements.length; i++) {
                if (this.elements[i].id == id) {
                    this.elements.splice(i, 1)
                    break
                }
            }
        },
        newLanguage():LanguageElement {
            let ln = { id: this.nextLanguageId++, name: "语言" + this.nextLanguageId }
            console.log(ln)
            this.languages.push(ln)
            return ln
        },
        deleteLanguage(id: number) {
            let idx = this.languages.findIndex(item => item.id === id);
            this.languages.splice(idx, 1)
            for (let i = 0; i < this.elements.length; i++) {
                this.elements[i].texts.splice(idx, 1)
            }
            electron.ipcRenderer.send("deleteLanguage", id)
        },
        // 新增创建分组方法
        createGroup(name: string="", desc: string = "") {
            const newGroup = {
                groupId: this.nextGroupId++,
                name,
                desc,
                elementIds: []
            };
            this.groups.push(newGroup);
            return newGroup;
        },

        getText(id:number) {
            return this.elements.find(item => item.id === id);
        },
        getTextById(id:number) {
            for (let i = 0; i < this.elements.length; i++) {
                if (this.elements[i].id == id) {
                    return this.elements[i].texts[0]
                }
            }
            return "文本缺失"
        }
    }
});